package com.mamingchao.basic.rmi;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;
import java.rmi.server.RMIServerSocketFactory;

/**
 * Created by mamingchao on 2021/1/23.
 */
public class ProviderSocketFactory implements RMIServerSocketFactory {
    /**
     * Create a server socket on the specified port (port 0 indicates
     * an anonymous port).
     *
     * @param port the port number
     * @return the server socket on the specified port
     * @throws IOException if an I/O error occurs during server socket
     *                     creation
     * @since 1.2
     */
    @Override
    public ServerSocket createServerSocket(int port) throws IOException {
        ServerSocket server = new ServerSocket(port);

        Socket socket = server.accept();
        InputStream inputStream = socket.getInputStream();
        /*****************CharBuffer 使用********************/
        InputStreamReader reader = new InputStreamReader(inputStream);
        CharBuffer cb = CharBuffer.allocate(1024);
        reader.read(cb);
        char[] charContent = cb.array();
        String strContent = cb.toString();
        System.out.println("CharBuffer - Server endpoint receive message " + strContent);

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(strContent.getBytes());

        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        if ((len = inputStream.read(bytes)) != 0) {
            sb.append(bytes);
        }

        System.out.println("bytes[]-Server endpoint receive message " + sb.toString());
        outputStream.write(strContent.getBytes());


        return server;
    }
}
